package com.dst.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.dst.eneity.Jar;
import com.dst.service.JarService;
import com.dst.service.impl.JarServiceImpl;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/jar")
public class JarController {
    JarService jarService = new JarServiceImpl();
    @RequestMapping("/selectAll")
    public String selectAll(Model model){
        List<Jar> jars = jarService.selectAll();
        model.addAttribute("jars",jars);
        return "/showAll.jsp";
    }
    @RequestMapping("/upload")
    public String upload(MultipartFile mf,String description) throws IOException {
        String originalFilename = mf.getOriginalFilename();
        String s = UUID.randomUUID().toString();
        String f=s+originalFilename;
        File file = new File("D:/Test/"+f);
        mf.transferTo(file);
        int size = (int)mf.getSize();
        Jar jar = new Jar(null,originalFilename,size,description,f);
        jarService.insert(jar);

        return "redirect:/jar/selectAll.do";
    }
    @RequestMapping("download")
    public void download(String filename,String name, HttpServletResponse resp) throws IOException {
        File file = new File("d:/test/" + filename);
        resp.setHeader("content-disposition","attachment;fileName="+name+"");
        FileUtils.copyFile(file,resp.getOutputStream());
    }
    @RequestMapping("input")
    public String input(MultipartFile mf) throws Exception {
        InputStream inputStream = mf.getInputStream();
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        importParams.setHeadRows(1);
        List<Jar> jar = ExcelImportUtil.importExcel(inputStream, Jar.class, importParams);
        for (Jar j:jar
             ) {
            jarService.insert(j);
        }
        return "redirect:/jar/selectAll.do";
    }
@RequestMapping("/output")
    public void output(HttpServletResponse resp) throws IOException {
    List<Jar> jars = jarService.selectAll();
    ExportParams exportParams = new ExportParams("hh","hh");
    Workbook sheets = ExcelExportUtil.exportExcel(exportParams,Jar.class,jars);
    resp.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode("Hh.xls","utf-8"));
    sheets.write(resp.getOutputStream());
}
}
